package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.PageResult;
import com.tanhua.model.domain.mongo.RecommendUser;
import com.tanhua.model.domain.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author lk
 * @date 2022-03-25
 */
@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询今日佳人
    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //根据toUserId(当前用户的id)查询，根据评分score排序，获取第一条
        //构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //构建Query对象                           按照分数排序,从高到低,每页只查一条
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        //调用mongoTemplate查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    //今日佳人
    @Override
    public PageResult queryRecommendUserList(Integer page, Integer pagesize, Long toUserId) {
        //构建Criteria对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //构建Query对象  添加条件 每页条数,从第几条查起
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(pagesize).skip((page - 1) * pagesize);
        //调用mongoTemplate查询
        List<RecommendUser> recommendList = mongoTemplate.find(query, RecommendUser.class);
        //查询总条数
        long count = mongoTemplate.count(query, RecommendUser.class);
        //构建返回值PageResult
        return new PageResult(page, pagesize, (int) count, recommendList);

    }

    //查询我的佳人
    @Override
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        //通过id查询佳人
        Query query = Query.query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //判断有没有佳人
        if (recommendUser == null) {
            //没有则创建一个
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            //构建缘分值
            recommendUser.setScore(95d);
        }
        return recommendUser;
    }

    //调用推荐API查询数据列表（排除喜欢/不喜欢的用户，数量限制）
    @Override
    public List<RecommendUser> queryCardsList(Long userId, int count) {
        //查询喜欢/不喜欢的用户
        List<UserLike> userLikes = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), UserLike.class);
        //抽取喜欢/不喜欢用户的 ID
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        //构造查询推荐用户的条件,查询时需要排除喜欢和不喜欢的用户                               nin = not in
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);
        //使用统计函数，随机获取推荐的用户列表
        TypedAggregation<RecommendUser> recommendUserTypedAggregation = TypedAggregation.newAggregation(RecommendUser.class,
                Aggregation.match(criteria),  //指定查询条件
                Aggregation.sample(count));//sample:抽样  随机获取指定个数

        AggregationResults<RecommendUser> results = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        //构造返回
        return results.getMappedResults();
    }
}
